<template>
  <div class="history-view module-container">
    <div class="module-header">
      <h2>历史记录</h2>
      <p class="module-description">查看和管理所有请求历史</p>
    </div>

    <div class="module-content">
      <div class="history-toolbar">
        <el-input
          v-model="searchText"
          placeholder="搜索历史记录..."
          prefix-icon="el-icon-search"
          style="width: 300px"
          @input="updateFilter"
        />
        
        <el-select v-model="filterType" @change="updateFilter" style="width: 150px">
          <el-option label="全部类型" value="all" />
          <el-option label="HTTP" value="http" />
          <el-option label="MQTT" value="mqtt" />
          <el-option label="WebSocket" value="websocket" />
        </el-select>
        
        <div style="flex: 1"></div>
        
        <el-button @click="exportHistory">导出历史</el-button>
        <el-button @click="clearHistory" type="danger">清空历史</el-button>
      </div>

      <el-table
        :data="filteredItems"
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="history-detail">
              <pre>{{ JSON.stringify(props.row, null, 2) }}</pre>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" :type="getTypeColor(scope.row.type)">
              {{ scope.row.type.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="method" label="方法" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.method" size="mini">
              {{ scope.row.method }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="url" label="URL/主题" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.url || scope.row.topic || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.status" :class="getStatusClass(scope.row.status)">
              {{ scope.row.status }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="timestamp" label="时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.timestamp) }}
          </template>
        </el-table-column>
        
        <el-table-column align="center" label="操作" width="170">
          <template slot-scope="scope">
            <el-button style="padding-left: 5px;padding-right: 5px;" type="text" size="small" @click="replayItem(scope.row)">
              重放
            </el-button>
            <el-button style="padding-left: 5px;padding-right: 5px;"  type="text" size="small" @click="deleteItem(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="filteredItems.length === 0" class="empty-state">
        <i class="el-icon-folder-opened"></i>
        <p>暂无历史记录</p>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  name: 'History',
  data() {
    return {
      searchText: '',
      filterType: 'all'
    }
  },
  computed: {
    ...mapState('history', ['items']),
    ...mapGetters('history', ['filteredItems'])
  },
  created() {
    this.$store.dispatch('history/loadHistory')
  },
  methods: {
    ...mapActions('history', ['removeItem', 'clearHistory', 'setFilter']),
    
    updateFilter() {
      this.setFilter({ key: 'type', value: this.filterType })
      this.setFilter({ key: 'searchText', value: this.searchText })
    },
    
    handleRowClick(row) {
      // 展开/收起详情
    },
    
    replayItem(item) {
      if (item.type === 'http' && item.request) {
        this.$store.dispatch('httpClient/loadRequestFromHistory', item.request)
        this.$router.push('/http-client')
        this.$message.success('已加载到 HTTP 客户端')
      } else {
        this.$message.info('该类型暂不支持重放')
      }
    },
    
    deleteItem(item) {
      this.$confirm('确定删除该记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.removeItem(item.id)
        this.$message.success('已删除')
      })
    },
    
    exportHistory() {
      const data = JSON.stringify(this.filteredItems, null, 2)
      const blob = new Blob([data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `history_${Date.now()}.json`
      a.click()
      URL.revokeObjectURL(url)
      this.$message.success('导出成功')
    },
    
    clearHistory() {
      this.$confirm('确定清空所有历史记录？此操作不可恢复', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('history/clearHistory')
        this.$message.success('历史记录已清空')
      })
    },
    
    formatDateTime(timestamp) {
      return new Date(timestamp).toLocaleString()
    },
    
    getTypeColor(type) {
      const colors = {
        http: 'primary',
        mqtt: 'success',
        websocket: 'warning',
        tcp: 'info',
        udp: 'info'
      }
      return colors[type] || 'info'
    },
    
    getStatusClass(status) {
      if (status >= 200 && status < 300) return 'status-success'
      if (status >= 400) return 'status-error'
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../styles/variables.scss';

.history-view {
  .module-content {
    padding: $spacing-large;
  }
  
  .history-toolbar {
    display: flex;
    gap: $spacing-base;
    align-items: center;
    margin-bottom: $spacing-medium;
  }
  
  .history-detail {
    padding: $spacing-medium;
    background: #f5f5f5;
    
    pre {
      margin: 0;
      font-family: monospace;
      font-size: 12px;
    }
  }
  
  .empty-state {
    text-align: center;
    padding: $spacing-extra-large * 2;
    color: $text-secondary;
    
    i {
      font-size: 64px;
      margin-bottom: $spacing-medium;
    }
  }
  
  .status-success {
    color: $success-color;
  }
  
  .status-error {
    color: $danger-color;
  }
}
</style>